package com.wider.applets;
import java.awt.*;
//import javax.swing.*;
import java.applet.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.wider.foundation.channel.HttpChannel;
import com.wider.foundation.channel.HttpChannel.HttpResponseHandlerImpl;
import com.wider.servlet.MultipartFormData;
public class FileTestApplet extends Applet{
	
	
	private static final long serialVersionUID = 1L;
	
	Boolean keepgoing=true;
	int state=0;
	
	Button btn;
	int count=0;
	Choice chc=new Choice();
	List lst = new List(5,true);
	Panel downPnl=new Panel(new GridLayout(1,1));
	Panel pnl=new Panel(new GridLayout(3,1));
	Button btnUpload,btnUploadBrowse,test;
	Label[] lab=new Label[3];
	Button[] btnd=new Button[3];
	Button[] btnb=new Button[3];
	Label[] ttt=new Label[10];
	TextField upText=new TextField();
	int loop,loop2,meg;
	int totalFile;
	//comm_action together=new comm_action();
	Thread together=new Thread();

	
	
	public void init()
	{
		setGUI();
	}
public void start()
    {
	  
	    
	}

public void setGUI(){
	//set fram
	setSize(500,250);
	//download
	Label downLabel = new Label("download",Label.CENTER);
	pnl.add(downLabel);
	totalFile=1;
	//file label
	for(loop2=0;loop2<totalFile;loop2++){
		lab[loop2]=new Label("web.xml");
		btnd[loop2]=new Button("download");
		btnb[loop2]=new Button("browse");
		//btnb[loop2].addActionListener(new browseAction());
		btnd[loop2].addActionListener(new downloadAction());
		downPnl.add(lab[loop2]);
		downPnl.add(btnd[loop2]);
		downPnl.add(btnb[loop2]);
	}
	pnl.add(downPnl);
	Label upLabel = new Label("upload",Label.CENTER);
	pnl.add(upLabel);
	add(pnl);
	upText.setColumns(40);
	add(upText);
	btnUploadBrowse=new Button("browse");
	//btnUploadBrowse.addActionListener(new uploadPath());
	btnUpload=new Button("upload");
	test=new Button("test");
	btnUpload.addActionListener(new uploadAction());
	test.addActionListener(new check_click());
	add(btnUploadBrowse);
	add(btnUpload);
	add(test);
}

	
	public void paint(Graphics g)
	{
		
	}
	
	public class downloadAction implements ActionListener {
   		public void actionPerformed(ActionEvent e) {
        		Button btnTo=(Button) e.getSource();      //
		//download function
		//download_URL("web.xml","http://192.168.1.101:8080/test2/tx?file=web.xml");
        		
    download_URL("try2","http://localhost:8080/hello/tx");
 	   	}
	 }
	
	 
	 
	public void download_URL(String downloadname,String serverip){
		int meg;
		DataInputStream nin;
		FileOutputStream fout;
		URL webURL=null;
		try{
			webURL=new URL(serverip); 
         	}
         	catch(MalformedURLException e)
         	{
         		System.out.println("Error");
         	} 
 	        try
		{
			meg=0;
        		System.out.println("Ready to download");
        		nin=new DataInputStream(webURL.openStream());//con_S.getInputStream()
        		fout=new FileOutputStream("/home/sky/"+downloadname);
        		System.out.println("Starting........................");
			try{
				while(meg!=-1){
//		        		System.out.println("num is"+meg);
					meg=nin.readByte();
					fout.write(meg);		
				}
                	}
            	   	catch(IOException e){}
			finally{
				fout.close();
				nin.close();
			}
        		System.out.println("Download is OK");
		}
        	catch(IOException e){
/*           		System.out.println(e.toString());
         		e.printStackTrace();
          		System.exit(1);*/ 
		} 
          
        
        }
	
	class pause_th extends Thread
	{
	   comm_action com;
		public pause_th(comm_action com)
		{
			this.com=com;
		}
		public void run() 
		{
			com.pause();
		}
		
		
		
	}
	class comm_action{
		synchronized void upload_URL3(String uploadname,String serverip) 
	    {
	        int meg;
	   	URL webURL=null;
	   	//DataInputStream nin=null;
	   
	   	FileInputStream fin = null;
		try {
			fin = new FileInputStream("/home/sky/workspace/hello/WebContent/5.flv");
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	          //FileInputStream fin=null;
	         
		 OutputStream nout = null;
	       try{
	  //	webURL=new URL(serverip+"?fileName="+URLEncoder.encode(uploadname,"utf-8")); 
	    	   webURL=new URL(serverip); 
	           }
	       catch(MalformedURLException e){
	                 System.out.println("Error");
	           } 
	       try {
			//nin=new DataInputStream(webURL.openStream());
	    	   HttpURLConnection conn=(HttpURLConnection)webURL.openConnection();
	    	   conn.setRequestMethod("POST");
	   		   conn.setAllowUserInteraction(true);
	   		   conn.setDoInput(true);
	   		   conn.setDoOutput(true);
	   		   conn.setUseCaches(true);
	   		//conn.setRequestProperty("RANGE","bytes=10000-"); 
	   		conn.setRequestProperty("Content-type", "application/x-java-serialized-object"); 
	    	  conn.connect();
	    	  nout = conn.getOutputStream();
	    	/*  ObjectOutputStream objOutputStrm = new ObjectOutputStream(nout);
	    	  //objOutputStrm.writeObject(new String("hi new in")); 
	    	  objOutputStrm.writeObject(fin); 
	    	  objOutputStrm.flush(); 
	    	  objOutputStrm.close(); */
	    	  
	    	  
	    	 // InputStream inStrm = conn.getInputStream();
	    	   
	    	  System.out.println("ready");
	    	  int i=1;
	    		    	  while(((meg=fin.read())!=-1))    
		          { 
		    		// if(meg>10000)
		        	  nout.write(meg);	 
		        	  System.out.println("number "+i+" "+meg+" "+keepgoing+" ohoh");
		        	// if(i==10000)break;
		        	  
		        	  i++;
		        	  while(keepgoing==false)
		        	  {
		        		  
		        		  this.wait();
		        		  System.out.println("waiting");
		        		 
		        	  }
		        	  
		          }
	    	 
	    	 // 
	    	  InputStream inStrm = conn.getInputStream();
	    	  
	    	  fin.close();
	 		nout.close();
	    	//   int status = conn.getResponseCode();
	         //  System.out.println(status);

	    	 /*  conn.setRequestMethod("GET");
	   		   conn.setAllowUserInteraction(true);
	   		   conn.setDoInput(true);
	   		   conn.setDoOutput(true);
	   		   conn.setUseCaches(true);*/
	   		 
	    	   
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	       
	           try{
	    
	   	
	               try{
	   		
	                 /* while((meg=fin.read())!=-1)    
	                  { 
	                	  nout.write(meg);
	                	  System.out.println(meg);
	                  }*/

	                         
	                         /*  for(meg=50;meg<70;meg++)
	                          {
	                        	 
	            	             nout.write(meg);
	                        	   System.out.println(meg);
	                           }*/
	                  
	   		 //  fin.close();
	   		//	nout.close();
	                   }
	   		catch(Exception e){}           
	           
	            }
	      
	        catch(Exception e){
	           	System.out.println(e.toString());
	           	e.printStackTrace();
	           	System.exit(1); 
	   	}  
	    }
 
		synchronized void pause()
		{
			if(keepgoing==true)
     			keepgoing=false;
     		else
     			keepgoing=true;
     		
     		System.out.println(keepgoing);
     		 
	     		if(keepgoing)
	     			{
	     			this.notify();
	    			System.out.println("wake up");
	     			  
	     			}
		}
		
	}
	class upload_th extends Thread
	{
		comm_action com;
		public upload_th(comm_action com)
		{
			this.com=com;
		}
		public void run() 
		{
			com.upload_URL3("456.txt","http://localhost:8080/hello/tx");
			//upload_URL3("456.txt","http://localhost:8080/hello/tx");
		}
		
		
	}
	public class check_click implements ActionListener{
		public void actionPerformed(ActionEvent e) {
     		Button btnTo=(Button) e.getSource();      //
		//upload function
     		
     		// this.start();
     	
     		 Thread thread2 = new Thread(new Runnable() 
    		 {
                public void run() 
                {
                	System.out.println("in ----  2");
                if(state==0)
               	 {
               		state=1;
               		upload_URL3("http://localhost:8080/hello/tx");
          
               		
               	 }
                	if(keepgoing==true)
             			keepgoing=false;
             		else
             			keepgoing=true;
                	if(keepgoing==true)
                	{
                		//pause_th action=new pause_th(together);
        	     		//action.start();
                		synchronized(together){
                			together.notify();}
    	    			System.out.println("wake up");
                	}
                }
    		 });
     		 thread2.start();
	       	  
	   	}
	/*	public void run() 
		{
			pause_th action=new pause_th(together);
     		action.start();
		}
		public void start()
	    {
			 
			Thread act;
		    act=new Thread(this); 
		    act.start();
		    
		}*/
	/*	public void start()
	    {
			Thread act;
		    act=new Thread(this); 
		    act.start();
		    
		}
		synchronized void tell()
		{

			this.notifyAll();
			System.out.println("wake up");
		}
		@Override
		public void run() {
			// TODO Auto-generated method stub
		

     		if(keepgoing==true)
     			keepgoing=false;
     		else
     			keepgoing=true;
     		
     		System.out.println(keepgoing);
     		 
	     		if(keepgoing)
	     			{
	     			tell();
	     			  
	     			}
	    
			
		}*/
 }
	public class uploadAction implements ActionListener {
		public void actionPerformed(ActionEvent e) {
     		Button btnTo=(Button) e.getSource();      //
		//upload function
     		
     	//this.start();
     	
     		
     		/* Thread thread1 = new Thread(new Runnable() 
     		 {
                 public void run() 
                 {
                	
         			//upload_th action=new upload_th(together);
              		//action.start();
                	if(state==0)
                	 {
                		state=1;
                		upload_URL3("http://localhost:8080/hello/tx");
           
                		
                	 }
                	
                 }
     		 });
     		
     		
     		thread1.start();*/
     		//make_path_request();
     		senout3();
           
		}
     	
		
     
	//	upload_URL3("456.txt","http://localhost:8080/hello/tx");

  /*   		lenth("/home/sky/workspace/hello/WebContent/5.flv");
     		//this.run();
 	   this.start();
     		System.out.println(keepgoing);
     		
                 //  upload_URL2(String uploadname,String filepath,String serverip)			
	   	}
		public void run() 
		{
		//	upload_URL3("456.txt","http://localhost:8080/hello/tx");
			
		}
	public void start()
	    {
			Thread act;
		    act=new Thread(this); 
		    act.start();
		    
		}
*/
	//	}

	//	@Override
	/*	public void run() {
			// TODO Auto-generated method stub
			if(keepgoing==true)
     			keepgoing=false;
     		else
     			keepgoing=true;
			
			if(keepgoing==true)
			{
			upload_th action=new upload_th(together);
     		action.start();
			}
			else
			{
				pause_th action=new pause_th(together);
	     		action.start();
			}
		}
		public void start()
	    {
			 
			Thread act;
		    act=new Thread(this); 
		    act.start();
		    
		}*/
 }
	public void upload_URL2(String uploadname,String serverip)
    {
        int meg;
   	URL webURL=null;
          //FileInputStream fin=null;
         
           OutputStream nout = null;
           OutputStream nout2 = null;
       try{
  //	webURL=new URL(serverip+"?fileName="+URLEncoder.encode(uploadname,"utf-8")); 
    	   webURL=new URL(serverip); 
           }
       catch(MalformedURLException e){
                 System.out.println("Error");
           } 
           try{
 /*       	   HttpURLConnection conn=(HttpURLConnection)webURL.openConnection();
                //   conn.setRequestMethod("POST");
   		   conn.setAllowUserInteraction(true);
   		   conn.setDoInput(true);
   		   conn.setDoOutput(true);
   		   conn.setUseCaches(true);
   		   conn.setRequestProperty("Content-Type", "application/octet-stream");
              
             //    File upper=new File(filepath);
             //   fin=new FileInputStream(upper);
   		 //  	nout=new DataOutputStream ;
   		// nout=new DataOutputStream(webURL.openStream());
   	   nout = conn.getOutputStream();*/
        	   URLConnection conn=webURL.openConnection();
       conn.setDoOutput(true);   
    
        nout2=new DataOutputStream(conn.getOutputStream());
        
   	 System.out.println("ready");
               try{
   		
                  // while((meg=fin.read())!=-1)    
                    //    nout.write(meg);

                         
                           for(meg=50;meg<70;meg++)
                           {
                        	   nout2.write(meg);
                        	   System.out.println(meg);
                           }

   		  //    fin.close();
   			nout.close();
                   }
   		catch(IOException e){}           
           
            }
      
        catch(IOException e){
           	System.out.println(e.toString());
           	e.printStackTrace();
           	System.exit(1); 
   	}  
    }
	public void lenth(String path)
	{
		File fin = null;
		long str;
		fin = new File(path);
		str=fin.length(); 
		System.out.println(str);
	}
	
	public void sendout2()
	{
		 HashMap<Object, Object> params = new HashMap<Object, Object>();
		 params.put("name", "Coffee Lou");
	}
	public void make_path_request()
	{
		 try {
	            HttpChannel channel = new HttpChannel("http://localhost:8080/hello/echo");
	            
	            //String a[]=new String[10];
	            HashMap<Object, Object> params = new HashMap<Object, Object>();
	          params.put("id", 100);
	           /* params.put("name", "Coffee Lou");
	            params.put("weight", 23.3317);
	            params.put("power", "200%");*/
              
	           //  String path="/home";
	           // params.put("root", path);
	            HttpResponseHandlerImpl handler = new HttpResponseHandlerImpl(){
	                public void handle(int resp_code, String resp_mesg, InputStream stream_in) throws IOException {
	                  
	                	
	                	 MultipartFormData formdata = new MultipartFormData(stream_in,  6*1024*1024, 2*1024*1024);
	                     Iterator paramit = formdata.getParameterMap().entrySet().iterator();
	                     while(paramit.hasNext()){
	                         Map.Entry<Object, Object> param = (Map.Entry<Object, Object>) paramit.next();
	                         Object paramkey = param.getKey();
	                         Object paramval = param.getValue();
	                         System.out.println("Parameter1 : " + paramkey + " : " + paramval);
	                     }

	                	
	                }


	            };
	            
	            //channel.get(params, handler);

	            channel.post(params, handler);
	        }

	        catch (MalformedURLException ex){
	            Logger.getLogger(channelTest.class.getName()).log(Level.WARNING, "Malformed URL Exception", ex);
	        }        catch (Exception ex) {
	            Logger.getLogger(channelTest.class.getName()).log(Level.SEVERE, "Runtime Exception", ex);
	        }
			
			
		
	}
	public void senout3()
	{

		 try {
	            HttpChannel channel = new HttpChannel("http://localhost:8080/hello/echo");

	            HashMap<Object, Object> params = new HashMap<Object, Object>();
	         String path="/home";
		         params.put("root", path);
	          //  params.put("id", 100);
	            
	        

	            HttpResponseHandlerImpl handler = new HttpResponseHandlerImpl(){
	                public void handle(int resp_code, String resp_mesg, InputStream stream_in) throws IOException {
	                    BufferedReader reader = new BufferedReader(new InputStreamReader(stream_in));
	                    try {
	                        String line;
	                        while (null != (line = reader.readLine())){
	                            System.out.println(line);
	                        }
	                    } catch (IOException ex) {
	                        throw ex;
	                    }
	                	
	                	
	                }


	            };

	            //channel.get(params, handler);

	            channel.post(params, handler);
	        }

	        catch (MalformedURLException ex){
	            Logger.getLogger(channelTest.class.getName()).log(Level.WARNING, "Malformed URL Exception", ex);
	        }        catch (Exception ex) {
	            Logger.getLogger(channelTest.class.getName()).log(Level.SEVERE, "Runtime Exception", ex);
	        }

	    }
	public void senout()
	{

		 try {
	            HttpChannel channel = new HttpChannel("http://localhost:8080/hello/echo");

	            HashMap<Object, Object> params = new HashMap<Object, Object>();
	            params.put("id", 100);
	            params.put("name", "Coffee Lou");
	            params.put("weight", 23.3317);
	            params.put("power", "200%");
	            params.put("power1", "201%");
	            params.put("power2", "202%");
	            params.put("power3", "203%");
	            params.put("power4", "204%");
	            //params.put(new File("/home/sky/workspace/hello/WebContent/5.flv"), "kiki");
	        /*   HashMap<String, Object> params = new HashMap<String, Object>();
	            params.put("id", 100);
	            params.put("name", "Coffee Lou");
	            params.put("weight", 23.3317);
	            params.put("power", "200%");*/
	          //  params.put(new File("resources/kiki 1.jpg"), "kiki");
	         //   params.put(new File("resources/kiki 2.jpg"), "kiki");
	          //  params.put(new File("resources/copy 1.jpg"), "copy");
	          //  params.put(new File("resources/copy 2.jpg"), "copy");

	            HttpResponseHandlerImpl handler = new HttpResponseHandlerImpl(){
	                public void handle(int resp_code, String resp_mesg, InputStream stream_in) throws IOException {
	                    BufferedReader reader = new BufferedReader(new InputStreamReader(stream_in));
	                    try {
	                        String line;
	                        while (null != (line = reader.readLine())){
	                            System.out.println(line);
	                        }
	                    } catch (IOException ex) {
	                        throw ex;
	                    }
	                }


	            };

	            //channel.get(params, handler);

	            channel.post(params, handler);
	        }

	        catch (MalformedURLException ex){
	            Logger.getLogger(channelTest.class.getName()).log(Level.WARNING, "Malformed URL Exception", ex);
	        }        catch (Exception ex) {
	            Logger.getLogger(channelTest.class.getName()).log(Level.SEVERE, "Runtime Exception", ex);
	        }

	    }
	
	public void upload_URL3(String serverip) 
    {
        int meg;
        int i=1;
   	URL webURL=null;
   	//DataInputStream nin=null;
   	String path="/home/sky/workspace/hello/WebContent/5.flv";
   	FileInputStream fin = null;
	try {
		fin = new FileInputStream(path);
		
	} catch (FileNotFoundException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}
          //FileInputStream fin=null;
         
	 OutputStream nout = null;
       try{
  //	webURL=new URL(serverip+"?fileName="+URLEncoder.encode(uploadname,"utf-8")); 
    	   webURL=new URL(serverip); 
           }
       catch(MalformedURLException e){
                 System.out.println("Error");
           } 
       try {
		//nin=new DataInputStream(webURL.openStream());
    	   HttpURLConnection conn=(HttpURLConnection)webURL.openConnection();
    	   conn.setRequestMethod("POST");
   		   conn.setAllowUserInteraction(true);
   		   conn.setDoInput(true);
   		   conn.setDoOutput(true);
   		   conn.setUseCaches(true);
   		//conn.setRequestProperty("RANGE","bytes=10000-"); 
   		conn.setRequestProperty("Content-type", "application/x-java-serialized-object"); 
    	  conn.connect();
    	  nout = conn.getOutputStream();
    	  
    	/*  ObjectOutputStream objOutputStrm = new ObjectOutputStream(nout);
    	  //objOutputStrm.writeObject(new String("hi new in")); 
    	  objOutputStrm.writeObject(fin); 
    	  objOutputStrm.flush(); 
    	  objOutputStrm.close(); */
    	  
    	  
    	 // InputStream inStrm = conn.getInputStream();
    	   
    	 // System.out.println("ready");
    	  
    	  File file=new File(path);
 		 byte fileContent[] = new byte[1024];
    	  int hi;
    	 
    		   while(((meg=fin.read(fileContent))!=-1))    
	          { 
	    	
	         nout.write(fileContent,0,meg);	 
	        	  System.out.println("number "+i+" "+meg+" "+keepgoing+" "+state);
	        	
	        	  
	        	  i++;
	        	
	        		  
	        	  
	        	    if(keepgoing==false)
	        	    {
	        	    	synchronized(together)
	        	    	{
	        	    		together.wait();
	        	    		

	        	    	 }
	        		  System.out.println("waiting");
	        	    }
	        	  
	        	if(i%20000==0)
	        	{ hi=conn.getResponseCode(); 
	        	  System.out.println("hi is "+hi);
		        	
	        	
	        	}
	        	  
	          }
    		   lenth(path);
    	 // 
    	//  InputStream inStrm = conn.getInputStream();
    	  
    	  fin.close();
 		nout.close();
    	  int status = conn.getResponseCode();
           System.out.println(status);

    	 /*  conn.setRequestMethod("GET");
   		   conn.setAllowUserInteraction(true);
   		   conn.setDoInput(true);
   		   conn.setDoOutput(true);
   		   conn.setUseCaches(true);*/
   		 
    	   
	} catch (Exception e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}
       
       
    }


}

